<template>
  <div class="account-view">
    <h1>账户余额</h1>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      :message="error"
      type="error"
      :closable="true"
      @close="clearError"
    />
    
    <!-- 余额卡片 -->
    <div class="balance-card">
      <h2>当前余额</h2>
      <div class="balance-amount">
        <template v-if="loading">
          <el-skeleton :loading="true" active class="balance-skeleton" />
        </template>
        <template v-else>
          ¥{{ formattedBalance }}
        </template>
      </div>
      <el-button type="primary" @click="handleRecharge" :loading="loading">
        充值
      </el-button>
    </div>

    <!-- 余额明细 -->
    <div class="records-section">
      <h3>余额明细</h3>
      <div class="filter-bar">
        <el-select v-model="recordType" placeholder="所有类型" style="width: 150px; margin-right: 10px;">
          <el-option label="所有类型" value="" />
          <el-option label="充值" value="RECHARGE" />
          <el-option label="消费" value="CONSUME" />
          <el-option label="冻结" value="FROZEN" />
          <el-option label="解冻" value="UNFROZEN" />
          <el-option label="退款" value="REFUND" />
        </el-select>
        <el-button type="primary" @click="refreshRecords">
          查询
        </el-button>
      </div>
      
      <el-table
        v-loading="balanceRecordsLoading"
        :data="balanceRecords?.records || []"
        style="width: 100%; margin-top: 15px;"
        empty-text="暂无余额记录"
      >
        <el-table-column label="类型" width="100">
          <template #default="scope">
            {{ formatRecordType(scope.row.recordType) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="描述" />
        <el-table-column
          prop="amount"
          label="金额"
          width="120"
          :formatter="formatAmount"
          align="right"
        />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            {{ formatStatusText('SUCCESS') }}
          </template>
        </el-table-column>
        <el-table-column prop="balanceAfter" label="余额" width="100" align="right" :formatter="formatCurrency" />
      </el-table>
      <el-pagination
          v-if="balanceRecords"
          v-model:current-page="balanceRecords.page"
          v-model:page-size="balanceRecords.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="balanceRecords.total || 0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useAccountStore } from '@/stores/account/account';
import type { Ref } from 'vue';
import { toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { computed } from 'vue';
// Store
const accountStore = useAccountStore();
const {  loading, error, balanceRecords } = accountStore;
const balance = computed(() => accountStore.getBalance);
const router = useRouter();
// 余额明细加载状态
const balanceRecordsLoading = ref(false);
const formattedBalance = computed(() => accountStore.formattedBalance);
// 筛选条件
const recordType = ref<string>('');
const formatRecordType = (type: string): string => {
  const typeMap: {[key: string]: string} = {
    'RECHARGE': '充值',
    'CONSUME': '消费',
    'FROZEN': '冻结',
    'UNFROZEN': '解冻',
    'REFUND': '退款'
  };
  return typeMap[type] || type;
};

const formatStatusText = (status: string): string => {
  const statusMap: {[key: string]: string} = {
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PENDING': '处理中',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || '未知状态';
};
// 组件挂载时获取数据
 onMounted(async () => {
  try {
    await accountStore.fetchAccountBalance();
    console.log(balance?.value || 0);
    // console.log("lloohjkj"+accountStore.formattedBalance);
    fetchRecords()
  } catch (error) {
    console.error('获取账户余额失败:', error);
  }
  
});

// 获取记录
const fetchRecords = async () => {
  balanceRecordsLoading.value = true;
  try {
    const params: { page?: number; limit?: number; record_type?: string } = {
      page: balanceRecords?.page || 1,
      limit: balanceRecords?.pageSize || 10,
      record_type: recordType.value || undefined
    };
    
    await accountStore.fetchBalanceRecords(params);
  } catch (err) {
    console.error('获取余额明细失败:', err);
  } finally {
    balanceRecordsLoading.value = false;
  }
};

// 刷新记录
const refreshRecords = () => {
  if (balanceRecords) {
    balanceRecords.page = 1;
  }
  fetchRecords();
};

// 充值处理
const handleRecharge = async () => {
  try {
    // 跳转到充值页面
    router.push({
      path: '/account/recharge',
    });
  } catch (error) {
    // 用户取消操作
  }
};

// 格式化金额，增加正负号
const formatAmount = (row: any) => {
  const amount = row.amount;
  const sign = amount >= 0 ? '+' : '';
  return `${sign}¥${Math.abs(amount).toFixed(2)}`;
};

// 格式化货币
const formatCurrency = (row: any, column: any, value: number) => {
  const balanceValue = value || row.balanceAfter || 0;
  return `¥${balanceValue.toFixed(2)}`;
};

// 分页处理
const handleSizeChange = (size: number) => {
  if (balanceRecords) {
    balanceRecords.pageSize = size;
    fetchRecords();
  }
};

const handleCurrentChange = (current: number) => {
  if (balanceRecords) {
    balanceRecords.page = current;
    fetchRecords();
  }
};

// 清除错误
const clearError = () => {
  accountStore.clearError();
};
</script>

<style scoped>
.account-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.balance-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 30px;
  text-align: center;
}

.balance-card h2 {
  margin-bottom: 20px;
  color: #666;
  font-size: 18px;
}

.balance-amount {
  font-size: 36px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 20px;
}

.balance-skeleton {
  height: 40px;
  width: 150px;
  margin: 0 auto;
}

.records-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.records-section h3 {
  margin-bottom: 20px;
  font-size: 18px;
}

.filter-bar {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
}
</style>